import { createRouter, createWebHistory } from 'vue-router'
import routes from './router'
import useStore  from '@/store/index'
const store = useStore
const router = createRouter({
  history: createWebHistory(process.env.VUE_APP_BASE_URL),
  routes: [
    ...routes,
    {
      path: '/404', // 路由没有找到 万能的路由来显示 404 页面
      component: () => import('@/components/404.vue'),
      meta: {
        title: '404',
      },
    }
  ],
  scrollBehavior (to) {
    // return 期望滚动到哪个的位置
    if(to) {
      return { top: 0 }
    }else {
      return {}
    }
  }
})
router.beforeEach((to) => {
  const token = store.getters.getToken
  console.log(token);
  if(to.matched.length === 0) { // 判断路由不存在
    router.push({path: '/404'})
    return true
  }
  if(to.meta.requireAuth) { //判断是否需要登录
    if(token !== null) {// 已登录
      // 获取登录人的信息
      if(store.getters.getUserDetail) {
        return true
      }else {
        store.dispatch('getUserDetail').then(() => {
          return true 
        })
      }
    }else {
      router.push({path: '/login'})
      return false
    }
  }
  return true
})

export default router
